package com.fingard.dsp.distribute.bocom12;


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.fingard.FGBiz;
import com.fingard.dsp.distribute.dstrbset.DstrbItem;


public class BOCOM12Listener implements Runnable {
	
	private DstrbItem dstrbItem;
	private int listenType = 0;
	private int portType = 0;
	/**
	 * @param p_listenType 1接收客户端，发服务器，2接收服务端，发客户端
	 * @param p_portType 1联机交易，2文件
	 * */
	public BOCOM12Listener(DstrbItem p_dstrbItem, int p_listenType, int p_portType) {
		dstrbItem = p_dstrbItem;
		listenType = p_listenType;
		portType = p_portType;
	}
	
	ServerSocket socketServer;
	
	public void run() {
		try {
			
			int listenPort = 0;
			if(listenType == 1){//接收客户端，发服务器
				if(portType == 1){
					listenPort = Integer.valueOf(dstrbItem.portForDSP);
					socketServer = new ServerSocket(listenPort, 50);
					FGBiz.startLog.addLog(dstrbItem.dstrbCode+"开启接收客户端联机交易侦听端口：" + dstrbItem.portForDSP+"，DSP发报文连此端口");
				}
				else{
					listenPort = Integer.valueOf(dstrbItem.filePortForDSP);
					socketServer = new ServerSocket(listenPort, 50);
					FGBiz.startLog.addLog(dstrbItem.dstrbCode+"开启接收客户端文件侦听端口：" + dstrbItem.filePortForDSP+"，DSP发文件连此端口");
				}
			}
			else if(listenType == 2){//接收服务端，发客户端
				if(portType == 1){
					listenPort = Integer.valueOf(dstrbItem.portForBank);
					socketServer = new ServerSocket(listenPort, 50);
					FGBiz.startLog.addLog(dstrbItem.dstrbCode+"开启接收服务端联机交易侦听端口：" + dstrbItem.portForBank+"，银行发报文连此端口");
				}
				else{
					listenPort = Integer.valueOf(dstrbItem.filePortForBank);
					socketServer = new ServerSocket(listenPort, 50);
					FGBiz.startLog.addLog(dstrbItem.dstrbCode+"开启接收服务端文件侦听端口：" + dstrbItem.filePortForBank+"，银行发文件连此端口");
				}
			}
			else{
				FGBiz.startLog.addLogNoTime("distribute.bocom12.BOCOM12Listener无需开启侦听");
				return;
			}
			int tmpSeq=0;
			while (true) {
				tmpSeq++;
				Socket tmpSocket = socketServer.accept();
				tmpSocket.setSoTimeout(120000);
				FGBiz.startLog.addLogNoTime("distribute.bocom12.BOCOM12Listener.SoTimeout:"+tmpSocket.getSoTimeout());
				BOCOM12Dispatcher eachThread = new BOCOM12Dispatcher(dstrbItem, listenType, portType, tmpSocket);
				eachThread.listenPort = listenPort;
				eachThread.seqIDInner = tmpSeq;
    			new Thread(eachThread).start();
			}
			
		} catch (Exception ex) {
			FGBiz.startLog.exception("distribute.bocom12.BOCOM12Listener",ex);
		}
		
	}
	
	public void close() {
		if(socketServer != null){
    		try {
    			socketServer.close();
			} catch (IOException e) {
				FGBiz.startLog.exception("distribute.bocom12.BOCOM12Listener.close",e);
			}
    	}
	}
	
	
}
